#include <iostream>
#include <cstring>
#include <unistd.h>

const int num = 2;
const int size = 64;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER; // 条件变量


void *Wait(void *args)
{
    char *name = static_cast<char *>(args);
    while (true)
    {
        pthread_mutex_lock(&gmutex);
        pthread_cond_wait(&gcond, &gmutex); // 唤醒一个，打印一个；再wai时就排在了队列后面
        if (strcmp(name, "thread-1") == 0)
            std::cout << "线程A打印-我是线程A " << name << std::endl;
        else if (strcmp(name, "thread-2") == 0)
            std::cout << "线程B打印-我是线程B " << name << std::endl;
        else
            std::cout << "I am " << name << std::endl;
        pthread_mutex_unlock(&gmutex);
        usleep(10000);
    }

    delete name;
    return nullptr;
}

int main()
{
    pthread_t threads[num]; // 存放多线程的tid
    // 创建线程
    for (int i = 1; i <= num; i++)
    {
        char *name = new char[size];
        // std::cout << sizeof(name) << std::endl;
        snprintf(name, size, "thread-%d", i);
        pthread_create(threads + i, nullptr, Wait, (void *)name);
        usleep(20000);
    }

    // 主线程唤醒其它线程
    while (true)
    {   
        pthread_cond_signal(&gcond); // 唤醒一个
        // pthread_cond_broadcast(&gcond);
        sleep(1);
    }

    // 等待线程
    for (auto &e : threads)
    {
        pthread_join(e, nullptr);
    }

    return 0;
}